/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */

package net.cyweb.cloud.admin.handler;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.cyweb.cloud.admin.api.dto.UserDTO;
import net.cyweb.cloud.admin.api.dto.UserInfo;
import net.cyweb.cloud.admin.api.entity.SysSocialDetails;
import net.cyweb.cloud.admin.api.entity.SysUser;
import net.cyweb.cloud.admin.mapper.SysSocialDetailsMapper;
import net.cyweb.cloud.admin.service.SysUserService;
import net.cyweb.cloud.common.core.constant.SecurityConstants;
import net.cyweb.cloud.common.core.constant.enums.LoginTypeEnum;
import net.cyweb.cloud.common.core.exception.CheckedException;
import net.cyweb.cloud.common.core.util.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author cloud
 * @date 2019年11月02日
 * <p>
 * 微信小程序
 */
@Slf4j
@Component("MINI")
@AllArgsConstructor
public class MiniAppLoginHandler extends AbstractLoginHandler {

	private final SysUserService sysUserService;

	private final SysSocialDetailsMapper sysSocialDetailsMapper;

	/**
	 * 小程序登录传入code
	 * <p>
	 * 通过code 调用qq 获取唯一标识
	 *
	 * @param code
	 * @return
	 */
	@Override
	public String identify(String code) {
		SysSocialDetails condition = new SysSocialDetails();
		condition.setType(LoginTypeEnum.MINI_APP.getType());
		SysSocialDetails socialDetails = sysSocialDetailsMapper.selectOne(new QueryWrapper<>(condition));

		String url = String.format(SecurityConstants.MINI_APP_AUTHORIZATION_CODE_URL, socialDetails.getAppId(),
				socialDetails.getAppSecret(), code);
		String result = HttpUtil.get(url);
		log.debug("微信小程序响应报文:{}", result);
		JSONObject resultJsonObj = JSONUtil.parseObj(result);

		if (resultJsonObj.containsKey("errcode")) {
			log.error("微信小程序登录失败:{}", result);
			throw new CheckedException("微信小程序登录失败");
		}

		Object obj = resultJsonObj.get("openid");
		return obj.toString();
	}

	/**
	 * 根据openId获取用户信息
	 *
	 * @param openId 用户openId
	 * @return 用户信息对象，未找到时返回null
	 */
	@Override
	public UserInfo info(String openId) {
		UserDTO userDTO = new UserDTO();
		userDTO.setMiniOpenid(openId);

		R<UserInfo> userInfoR = sysUserService.getUserInfo(userDTO);

		if (userInfoR.getData() == null) {
			log.info("小程序不存在用户:{}", openId);
			return null;
		}

		return userInfoR.getData();
	}

	/**
	 * 绑定逻辑
	 *
	 * @param user     用户实体
	 * @param identify 渠道返回唯一标识
	 * @return
	 */
	@Override
	public Boolean bind(SysUser user, String identify) {
		user.setMiniOpenid(identify);
		sysUserService.updateById(user);
		return true;
	}

}
